package com.managedBean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import com.controller.ItemsController;
import com.dto.Item;
import com.managedBean.cart.CartManagedBean;
import com.utils.JsfUtils;

@ManagedBean(name = "searchManagedBean")
@ViewScoped
public class SearchManagedBean implements Serializable {
	private static final long serialVersionUID = 2364989608774096396L;
	private List<Item> itemsList;
	private Item selectedItem;
	@ManagedProperty(value = "#{itemsController}")
	private ItemsController itemsController;

	public SearchManagedBean() {
		itemsList = new ArrayList<Item>();
	}

	public List<Item> search(String str) {
		itemsList = itemsController.findByKeyword(str);
		return itemsList;
	}

	public void addToCart() {
		CartManagedBean cart = (CartManagedBean) JsfUtils
				.getBeanInstanceFromFacesContext("cart");
		String itemId = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap()
				.get("item");
		for(Item var:itemsList){
			if(String.valueOf(var.getItemId()).equals(itemId)){
				cart.addToCart(var);
				break;
			}
		}
		
	}
	/**
	 * @return the itemsList
	 */
	public List<Item> getItemsList() {
		return itemsList;
	}

	/**
	 * @param itemsList
	 *            the itemsList to set
	 */
	public void setItemsList(List<Item> itemsList) {
		this.itemsList = itemsList;
	}

	/**
	 * @return the selectedItem
	 */
	public Item getSelectedItem() {
		return selectedItem;
	}

	/**
	 * @param selectedItem
	 *            the selectedItem to set
	 */
	public void setSelectedItem(Item selectedItem) {
		this.selectedItem = selectedItem;
	}

	/**
	 * @return the itemsController
	 */
	public ItemsController getItemsController() {
		return itemsController;
	}

	/**
	 * @param itemsController
	 *            the itemsController to set
	 */
	public void setItemsController(ItemsController itemsController) {
		this.itemsController = itemsController;
	}
}
